//
//  DnpMemory.m
//  dnp_plugin
//
//

#import "DnpMemory.h"
#import <sys/mount.h>
#include <mach/mach.h>

@implementation DnpMemory

+ (NSDictionary *)treasures {
    return @{
        @"clasped" : [self claspedSize],
        @"over" : [self overSize],
        @"handed" : [self handedSize],
        @"stay" : [self staySize]
    };
}

// 总内存
+ (NSString *)handedSize {
    long long handedSize = [NSProcessInfo processInfo].physicalMemory;
    return [NSString stringWithFormat:@"%lld", handedSize];
}

// 可用内存
+ (NSString *)staySize {
    vm_statistics_data_t vmDnpStatistics;
    mach_msg_type_number_t machDnpNumber = HOST_VM_INFO_COUNT;
    kern_return_t result = host_statistics(mach_host_self(), HOST_VM_INFO, (host_info_t)&vmDnpStatistics, &machDnpNumber);
    if (result != KERN_SUCCESS) {
        return @"";
    }
    
    long long result1 = (unsigned long long)vmDnpStatistics.free_count * vm_page_size;
    long long result2 = (unsigned long long)vmDnpStatistics.inactive_count * vm_page_size;
    return [NSString stringWithFormat:@"%lld", result1 + result2];
}

// 总存储
+ (NSString *)overSize {
    struct statfs sta;
    unsigned long long overSize = -1;
    if (statfs("/var", &sta) >= 0) {
        long long result1 = sta.f_bsize;
        long long result2 = sta.f_blocks;
        overSize = (unsigned long long)(result1 * result2);
    }
    return [NSString stringWithFormat:@"%lld",overSize];
}

// 可用存储
+ (NSString *)claspedSize {
    
    NSError *error = nil;
    
    NSURL *tempDnpDirURL = [NSURL fileURLWithPath:NSTemporaryDirectory() isDirectory:YES];
    
    NSArray<NSURLResourceKey> *documentKeys = @[
       NSURLVolumeAvailableCapacityForImportantUsageKey,
   ];
    
    NSDictionary *documents = [tempDnpDirURL resourceValuesForKeys:documentKeys error:&error];
    
    if(error){return @"0";}

    NSNumber *claspedSize = documents[NSURLVolumeAvailableCapacityForImportantUsageKey];
    
    return [NSString stringWithFormat:@"%lld",claspedSize.longLongValue];
}

@end
